package com.xhs.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xhs.dto.request.AddCompanyParams;
import com.xhs.entity.CapCompanyInfoEntity;
import com.xhs.mapper.CapCompanyInfoMapper;
import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import com.xhs.service.CapCompanyInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.xhs.entity.table.CapCompanyInfoEntityTableDef.CAP_COMPANY_INFO_ENTITY;

/**
 * 企业信息 服务层实现。
 *
 * @author xhs
 * @since 2023-08-13
 */
@Slf4j
@Service
public class CapCompanyInfoServiceImpl extends ServiceImpl<CapCompanyInfoMapper, CapCompanyInfoEntity> implements CapCompanyInfoService {
    @Resource
    private CapCompanyInfoMapper companyInfoMapper;

    /**
     * 获取用户信息
     *
     * @return List<CapCompanyInfoEntity>
     */
    @Override
    public ReturnResult<Object> getCompanyInfo() {
        log.info("-------------获取用户信息------------------");
        List<CapCompanyInfoEntity> list = queryChain()
                .select(CAP_COMPANY_INFO_ENTITY.DEFAULT_COLUMNS)
                .from(CAP_COMPANY_INFO_ENTITY)
                .list();
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(list);
    }

    /**
     * 新增企业
     *
     * @param addCompanyParams 入参
     * @return ReturnResult<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult<Object> addCompanyInfo(AddCompanyParams addCompanyParams) {
        CapCompanyInfoEntity companyInfoEntity = queryChain().select(CAP_COMPANY_INFO_ENTITY.COMPANY_NAME)
                .from(CAP_COMPANY_INFO_ENTITY)
                .where(CAP_COMPANY_INFO_ENTITY.COMPANY_NAME.eq(addCompanyParams.getCompanyName()))
                .one();
        if (companyInfoEntity != null) {
            return ReturnResult.build(Result.DATA_EXISTENT);
        }
        CapCompanyInfoEntity entity = CapCompanyInfoEntity.builder()
                .companyName(addCompanyParams.getCompanyName())
                .companyId("F" + IdUtil.getSnowflakeNextId())
                .build();
        boolean save = save(entity);
        if (save) {
            JSONObject object = new JSONObject();
            object.set("id", entity.getId());
            object.set("name", entity.getCompanyName());
            object.set("no", entity.getCompanyId());
            return ReturnResult.build(Result.QUERY_SUCCESS).setData(object);
        }
        return ReturnResult.build(Result.ADD_ERROR);
    }

    /**
     * 获取企业信息
     *
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> getList() {
        List<CapCompanyInfoEntity> list = companyInfoMapper.getList();
        return ReturnResult.success("查询成功", list);
    }
}
